/**
 * @Copyright © 2018 普信恒业科技发展（北京）有限公司 保留所有权利
 */
package com.qgzj.util;

import com.alibaba.fastjson.JSON;
import com.qgzj.exception.QgzjException;
import com.qgzj.exception.QgzjStudyExceptionEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Description: 思必驰接口客户端类
 * 接口文档地址：
 * https://www.dui.ai/docs/ct_cloud_ASR_web(语音识别)
 * https://www.dui.ai/docs/ct_cloud_TTS_web(语音合成)
 * @Author: qinghuawang2@creditease.cn
 * @CreateTime: 2018/5/29 上午10:52
 */
@Component
public class DUIOkHttpClient {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${dui.tts.domain}")
    private String duiTtsDomain;

    /**
     * 将文字转换成语音
     *
     * @param text 待转换文字
     */
    public byte[] ttsJsoup(String text, String... param) {

        long begin = System.currentTimeMillis();
        String url = duiTtsDomain;

        String textType = "text";

        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("context", buildContext());
        if (param.length > 0 && "money".equals(param[0])) {
            bodyMap.put("request", buildTtsMoneyRequest(text, textType));
        } else {
            bodyMap.put("request", buildTtsRequest(text, textType));

        }
        String bodyJson = JSON.toJSONString(bodyMap);
        logger.debug("将文字转换成语音-jsoup，url={}, bodyJson={}", url, bodyJson);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");

        try {
            org.jsoup.Connection.Response content = JsoupUtil.getContent(url, bodyJson, null, headers);

            if (content.statusCode() != 200) {
                logger.warn("response.code={}, response={}", content.statusCode(), new String(content.bodyAsBytes()));
                throw new QgzjException(QgzjStudyExceptionEnum.TTS_FAILED);
            }

            //转换成功，接收到的是一段音频字节码
            logger.info("调用思必驰转换文本为语音成功-jsoup 接口= {} ,耗时= {} ,text= {}", url, (System.currentTimeMillis() - begin), text);
            return content.bodyAsBytes();
        } catch (Exception e) {
            logger.warn("调用思必驰接口异常-jsoup url: {}", url, e);
            throw new QgzjException(QgzjStudyExceptionEnum.TTS_FAILED);
        }
    }



    /**
     * 专门为金额调的语速方法
     *
     * @param text     合成语音文本
     * @param textType 文本类型
     * @return 请求tts参数
     */
    private Map<String, String> buildTtsMoneyMap(String text, String textType) {
        Map<String, String> param = new HashMap<>(16);
        param.put("text", text);
        param.put("textType", textType);
        param.put("voiceId", "hyanifa");
        param.put("language", "zh-CN");
        param.put("speed", "1");//语速 报金额的时候调的慢一点
        param.put("volume", "85");//音量0-100 默认80
        return param;
    }

    private Map<String, String> buildTtsMap(String text, String textType) {
        Map<String, String> param = new HashMap<>(16);
        param.put("text", text);
        param.put("textType", textType);
        param.put("voiceId", "hyanifa");
        param.put("language", "zh-CN");
        param.put("speed", "0.9");//语速 0.7-2 默认1
        param.put("volume", "85");//音量0-100 默认80
        return param;
    }

    private Map<String, Object> buildArsMap() {
        Map<String, Object> param = new HashMap<>(16);
        param.put("wakeupWord", "你好小驰");
        param.put("enableRealTimeFeedback", true);
        param.put("enableVAD", true);
        param.put("enablePunctuation", true);
        param.put("language", "zh-CN");
        param.put("res", "comm");
        param.put("lmId", "");

        return param;
    }

    private Map<String, Object> buildAudioMap() {
        Map<String, Object> param = new HashMap<>(16);
        param.put("audioType", "wav");
        param.put("sampleRate", 8000);
        param.put("channel", 1);
        param.put("sampleBytes", 2);
        return param;
    }

    /**
     * 调节金额的
     *
     * @param text
     * @param textType
     * @return
     */
    private Map<String, Object> buildTtsMoneyRequest(String text, String textType) {
        Map<String, Object> reqeustMap = new HashMap<>();
        reqeustMap.put("requestId", UUID.randomUUID());
        reqeustMap.put("tts", buildTtsMoneyMap(text, textType));
        reqeustMap.put("audio", buildAudioMap());

        return reqeustMap;
    }

    private Map<String, Object> buildTtsRequest(String text, String textType) {
        Map<String, Object> reqeustMap = new HashMap<>();
        reqeustMap.put("requestId", UUID.randomUUID());
        reqeustMap.put("tts", buildTtsMap(text, textType));
        reqeustMap.put("audio", buildAudioMap());

        return reqeustMap;
    }

    private Map<String, Object> buildAsrRequest() {
        Map<String, Object> reqeustMap = new HashMap<>();
        reqeustMap.put("requestId", UUID.randomUUID());
        reqeustMap.put("asr", buildArsMap());
        reqeustMap.put("audio", buildAudioMap());

        return reqeustMap;
    }

    private Map<String, Object> buildContext() {
        Map<String, Object> contextMap = new HashMap<>();

        return contextMap;
    }

    public static void main(String[] args) {
        DUIOkHttpClient client = new DUIOkHttpClient();
        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("context", client.buildContext());
        bodyMap.put("request", client.buildTtsRequest("我", "text"));

        String bodyJson = JSON.toJSONString(bodyMap);
        System.out.println(bodyJson);
    }
}
